/**
 * 
 */
package domain;
import java.util.*;

/**
 * @author it-equipment-selection team
 *
 */
public class BallotBox {
	
	private static BallotBox u;
	private Collection votes;
	private boolean votePeriod;

	protected BallotBox() {
		votes = new LinkedList();
	}

	public void addVote(User u, Product p) throws Exception {
		if (this.votePeriod){
			boolean find = false;
			Iterator it = votes.iterator();
			while (it.hasNext() && !find){
				Vote v = (Vote) it.next();
				if (v.getUser().equals(u) && v.getArticle().equals(p.getArticle()))
					find = true;
			}
			if (!find && p.isValid()){
				votes.add(new Vote(u,p));
				p.setNumVotes(p.getNumVotes()+1); 
			} else {
				throw new InvalidVoteException("Invalid vote");
			}
		} else {
			throw new InvalidPeriodException("Vote period not defined");
		}
	}

	public boolean isVotePeriod() {
		return votePeriod;
	}

	public void setVotePeriod(boolean votePeriod) {
		this.votePeriod = votePeriod;
	}	
	
	private class Vote {
		private User user;
		private Product product;
		private Article article;
		
		public Vote(User user, Product product) {
			this.user = user;
			this.product = product;
			this.article = product.getArticle();
		}

		public User getUser() {
			return user;
		}

		public Product getProduct() {
			return product;
		}

		public Article getArticle() {
			return article;
		}
		
	}
	
	public static synchronized BallotBox getInstance(){
		if (u == null) {
			u = new BallotBox();
		}
		return u;
	}
}
